package com.spice.im.chat;

import java.io.File;









import java.io.IOException;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


//import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.json.JSONException;
import org.json.JSONObject;

import com.speed.im.login.ContactGroupListIQ;
import com.speed.im.login.ContactGroupListIQResponse;
import com.speed.im.login.ContactGroupListIQResponseProvider;
import com.speed.im.login.EncryptionUtil;
//import com.spice.im.MainActivity;
import com.spice.im.ContactFrameActivity;
import com.spice.im.MainListActivity;
import com.spice.im.R;
//import com.spice.im.MainActivity.exPhoneCallListener;
import com.spice.im.chat.db.ChatMsgDao;
import com.spice.im.jspeex.voice.JSEncode;
import com.spice.im.jspeex.voice.JSpeexDec;
import com.spice.im.utils.AsyncTask;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;

//import dalvik.system.VMRuntime;


/**
 * 聊天界面
 *
 * @author 白玉梁
 * @blog http://blog.csdn.net/baiyuliang2013
 * @weibo http://weibo.com/2611894214/profile?topnav=1&wvr=6&is_all=1
 */
//@SuppressLint("SimpleDateFormat")
public class ChatActivity extends AppBaseActivity implements DropdownListView.OnRefreshListenerHeader,
        ChatAdapter.OnClickMsgListener,IConnectionStatusCallback {//, SpeechRecognizerUtil.RecoListener
    private ViewPager mViewPager;
    private LinearLayout mDotsLayout;
    private EditText input;
    private TextView send;
    private DropdownListView mListView;
    private ChatAdapter mLvAdapter;
    private ChatMsgDao msgDao;

    private LinearLayout chat_face_container, chat_add_container;
    private ImageView image_face;//表情图标
    private ImageView image_add;//更多图标
    private ImageView image_voice;//语音
    private TextView tv_weather,//图片
            tv_xingzuo,//拍照
            tv_joke,//笑话
            tv_loc,//位置
            tv_gg,//帅哥
            tv_mm,//美女
            tv_music;//歌曲
    
    private TextView voice_text;
    private ImageView image_keyboard;

    private LinearLayout ll_playing;//顶部正在播放布局
    private TextView tv_playing;

    //表情图标每页6列4行
    private int columns = 6;
    private int rows = 4;
    //每页显示的表情view
    private List<View> views = new ArrayList<View>();
    //表情列表
    private List<String> staticFacesList;
    //消息
    private List<Msg> listMsg;
    private SimpleDateFormat sd;
    private LayoutInflater inflater;
    private int offset;

    //发送者和接收者固定为小Q和自己
    private final String from = "xiaoq";//来自小Q
    private final String to = "master";//发送者为自己

    FinalHttp fh;
    AjaxParams ajaxParams;

    //在线音乐播放工具类
    MusicPlayManager musicPlayManager;
    // 语音听写工具
//    SpeechRecognizerUtil speechRecognizerUtil;
//    // 语音合成工具
//    SpeechSynthesizerUtil speechSynthesizerUtil;

    String voice_type;
    
    
	////////////20140210 start
	private String getRingRecordFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'speex'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".raw";//amr
	}
	private File file;
	private static final String PHOTOPATH2 = "beemphoto";
	private String RingRecordFilePath = "";
    final String start = Environment.getExternalStorageState();
    private static final String PHOTOPATH = "/beemphoto/"; 
    private String capturefilepath = "";
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
	//表情图标 biaoqing icon start 20130507
	private Dialog builder;
	private int[] imageIds = new int[107];
//	private TextView tvcontactname;
//	private String privatename="";
	private File fpath; 
//	private AudioRecorder mr;
//	private ARecorder mr;
    // 获取类的实例
    private ExtAudioRecorder recorder;
    //dialog显示的图片
    private Drawable[] micImages;
    
    
	private MediaPlayer mediaPlayer;
	private Thread recordThread;
	
	private static int MAX_TIME = 15;    //最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 1;     //最短录制时间，单位秒，0为无时间限制，建议设为1
	
	private static int RECORD_NO = 0;  //不在录音
	private static int RECORD_ING = 1;   //正在录音
	private static int RECODE_ED = 2;   //完成录音
	
	private static int RECODE_STATE = 0;      //录音的状态
	
	private static float recodeTime=0.0f;    //录音的时间
	private static double voiceValue=0.0;    //麦克风获取的音量值
	
	private ImageView dialog_img;
	private static boolean playState = false;  //播放状态
	private boolean isShosrt = false;
	private LinearLayout  voice_rcd_hint_loading,voice_rcd_hint_rcding,
			voice_rcd_hint_tooshort,voice_rcd_hint_toolong;//voice_rcd_hint_loading,
	private ImageView img1, sc_img1;
	private View rcChat_popup;
	private LinearLayout del_re;
	private ImageView volume;//录音动画图片
    public void setVolumeImage(Drawable drawable){
    	volume.setImageDrawable(drawable);
    }
	private boolean btn_vocie = false;
	private int flag = 1;
	private long startVoiceT, endVoiceT;
//	private Handler mVoiceHandler = new Handler();
//	private AnimationDrawable animationDrawable;  
//	private ImageView animationIV;
	////////////20140210 end

//    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mLvAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    Music music = (Music) msg.obj;
                    if (music == null) {
                        changeList(Const.MSG_TYPE_TEXT, "歌曲获取失败");
                    } else {
                        changeList(Const.MSG_TYPE_MUSIC, music.getMusicUrl() + Const.SPILT + music.getTitle() + Const.SPILT + music.getDescription());
                    }
                    break;
            }
        }
    };
    
    /** 设置Dialog的图片 */
    Handler volumeImagehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what<=6)
            setVolumeImage(micImages[msg.what]);
            else
            	setVolumeImage(micImages[6]);
        }
    };
    /** 录音失败的提示 */
    ExtAudioRecorder.RecorderListener listener = new ExtAudioRecorder.RecorderListener() {
        @Override
        public void recordFailed(FailRecorder failRecorder) {
            if (failRecorder.getType() == FailRecorder.FailType.NO_PERMISSION) {
                Toast.makeText(ChatActivity.this, "录音失败，可能是没有给权限", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ChatActivity.this, "发生了未知错误", Toast.LENGTH_SHORT).show();
            }
        }
    };
    
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
    	LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}
	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private LoadingDialog loadingDialog;
    private Context mContext;
    
    
    private String jid = "";

//	@Override
//	public void onBackPressed() {//逻辑放到onKeyDown(int keyCode, KeyEvent event)中
//		Log.d("================20170507 ChatActivity onBackPressed================", "+++++++onBackPressed+++++++jid="+jid);
//			//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
//			Intent i = new Intent(ChatActivity.this,MainListActivity.class);//ContactListPullRefListActivity
//			i.putExtra("jid",jid);
//			startActivity(i);
//			finish();
//			return;
//	}
//    @SuppressLint("ShowToast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
//    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理 
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        mContext = this;
        loadingDialog = new LoadingDialog(this);
        initTitleBar("消息", "小Q", "", this);
        musicPlayManager = new MusicPlayManager();
        fh = new FinalHttp();
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        sd = new SimpleDateFormat("MM-dd HH:mm");
        msgDao = new ChatMsgDao(this);
        staticFacesList = ExpressionUtil.initStaticFaces(this);
        voice_type = PreferencesUtils.getSharePreStr(this, Const.IM_VOICE_TPPE);
        
        
        micImages = getRecordAnimPic(getResources());
        AuditRecorderConfiguration configuration = new AuditRecorderConfiguration.Builder()
        .recorderListener(listener)
        .handler(volumeImagehandler)
        .uncompressed(true)
        .builder();

        recorder = new ExtAudioRecorder(configuration);
        
        
        jid = getIntent().getStringExtra("jid");
        if(jid==null || jid.equalsIgnoreCase("null"))
        	jid = "";
        Log.d("================20170507 ChatActivity onCreate================", "+++++++onCreate+++++++jid="+jid);
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        //初始化控件
        initViews();
        //初始化表情
        initViewPager();
        //初始化更多选项（即表情图标右侧"+"号内容）
        initAdd();
        //初始化数据
        initData();
        //初始化语音听写及合成部分
//        initSpeech();
        
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
	    
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
    }

//    private void initSpeech() {
//        speechRecognizerUtil = new SpeechRecognizerUtil(this);
//        speechRecognizerUtil.setRecoListener(this);
////        speechSynthesizerUtil = new SpeechSynthesizerUtil(this);
//    }

    /**
     * 初始化控件
     */
    private void initViews() {
//        mNetErrorView = findViewById(R.id.net_status_bar_top);
//        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
//        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
//        mConnect_status_btn.setOnClickListener(this);
        
        ll_playing = (LinearLayout) findViewById(R.id.ll_playing);
        tv_playing = (TextView) findViewById(R.id.tv_playing);

        mListView = (DropdownListView) findViewById(R.id.message_chat_listview);
//        SysUtils.setOverScrollMode(mListView);

        image_face = (ImageView) findViewById(R.id.image_face); //表情图标
        image_add = (ImageView) findViewById(R.id.image_add);//更多图标
        image_voice = (ImageView) findViewById(R.id.image_voice);//语音
        voice_text =  (TextView) findViewById(R.id.voice_text);//按住说话
        image_keyboard = (ImageView) findViewById(R.id.image_keyboard);//键盘文字输入
        chat_face_container = (LinearLayout) findViewById(R.id.chat_face_container);//表情布局
        chat_add_container = (LinearLayout) findViewById(R.id.chat_add_container);//更多

        mViewPager = (ViewPager) findViewById(R.id.face_viewpager);
        mViewPager.setOnPageChangeListener(new PageChange());
        //表情下小圆点
        mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);
        input = (EditText) findViewById(R.id.input_sms);
        send = (TextView) findViewById(R.id.send_sms);
        input.setOnClickListener(this);
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	voice_text.setVisibility(View.GONE);
            	input.setVisibility(View.VISIBLE);
//                image_voice.setVisibility(View.GONE);
                image_keyboard.setVisibility(View.GONE);
                if (s.length() > 0) {
                    send.setVisibility(View.VISIBLE);
                    image_voice.setVisibility(View.GONE);
                } else {
                    send.setVisibility(View.GONE);
                    image_voice.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        image_face.setOnClickListener(this);//表情按钮
        image_add.setOnClickListener(this);//更多按钮
        image_voice.setOnClickListener(this);//语音按钮
        image_keyboard.setOnClickListener(this);//键盘文字输入按钮
//        voice_text.setOnClickListener(this);
        send.setOnClickListener(this); // 发送

        mListView.setOnRefreshListenerHead(this);
        mListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
                    if (chat_face_container.getVisibility() == View.VISIBLE) {
                        chat_face_container.setVisibility(View.GONE);
                    }
                    if (chat_add_container.getVisibility() == View.VISIBLE) {
                        chat_add_container.setVisibility(View.GONE);
                    }
                    hideSoftInputView();
                }
                return false;
            }
        });
        
        //voice_text start
        initAudioRecordView();
        voice_text.setOnTouchListener(new View.OnTouchListener() {

    		@Override
    		public boolean onTouch(View v, MotionEvent event) {
//    			if (CommonUtils.isFastDoubleClick())
//    				return false;
    			
    			String str = new Random().nextInt()+"";
    			int action = event.getAction();

    			int[] location = new int[2];
    			voice_text.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
    			int btn_rc_Y = location[1];
    			int btn_rc_X = location[0];
    			int[] del_location = new int[2];
    			del_re.getLocationInWindow(del_location);
    			int del_Y = del_location[1];
    			int del_x = del_location[0];
    			
    			Log.e("※※※※※####语音20140808语音####※※※※※", "※※####语音20140808语音####※※btn_rc_Y="+btn_rc_Y
    					+";btn_rc_X="+btn_rc_X
    					+";del_Y="+del_Y
    					+";del_x="+del_x
    					+";event.getY()="+event.getY()
    					+";event.getX()="+event.getX());
    			
    			switch (action) {
    			case MotionEvent.ACTION_CANCEL:
    				v.setBackgroundResource(R.drawable.transparent);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					endVoiceT = SystemClock.currentThreadTimeMillis();
					flag = 1;
					if (recodeTime < MIX_TIME){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						voice_rcd_hint_toolong.setVisibility(View.GONE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}else if (recodeTime >= MAX_TIME && MAX_TIME != 0){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.GONE);
						voice_rcd_hint_toolong.setVisibility(View.VISIBLE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_toolong
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}
					//发送
					rcChat_popup.setVisibility(View.GONE);
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
					if (MAX_TIME>=recodeTime && recodeTime >= MIX_TIME)
					if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
//						sendOfflineFile(RingRecordFilePath,"audio");
						;
					}else{
						if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
							scanOldFile();
//							;
						}
    				Log.d("onTouchEvent action:ACTION_UP", "---onTouchEvent action:ACTION_UP");
					
    				break;
    			case MotionEvent.ACTION_UP:
    				v.setBackgroundResource(R.drawable.transparent);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					stop();
					endVoiceT = SystemClock.currentThreadTimeMillis();
					flag = 1;
					if (recodeTime < MIX_TIME){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
						voice_rcd_hint_toolong.setVisibility(View.GONE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_tooshort
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}else if (recodeTime >= MAX_TIME && MAX_TIME != 0){
						isShosrt = true;
						voice_rcd_hint_loading.setVisibility(View.GONE);
						voice_rcd_hint_rcding.setVisibility(View.GONE);
						voice_rcd_hint_tooshort.setVisibility(View.GONE);
						voice_rcd_hint_toolong.setVisibility(View.VISIBLE);
						volumeImagehandler.postDelayed(new Runnable() {
							public void run() {
								voice_rcd_hint_toolong
										.setVisibility(View.GONE);
								rcChat_popup.setVisibility(View.GONE);
								isShosrt = false;
							}
						}, 500);
						return false;
					}
					//发送
					rcChat_popup.setVisibility(View.GONE);
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
					if (MAX_TIME>=recodeTime && recodeTime >= MIX_TIME)
					if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
//						sendOfflineFile(RingRecordFilePath,"audio");
						;
					}else{
						if(RingRecordFilePath!=null && !RingRecordFilePath.equals(""))
						scanOldFile();
//							;
					}
    				Log.d("onTouchEvent action:ACTION_UP", "---onTouchEvent action:ACTION_UP");
    				break;
    			case MotionEvent.ACTION_DOWN:
//    				if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内
    				if (event.getY() > 0 && event.getX() > btn_rc_X) {
    					Log.e("※※※※※####语音20140808语音范围内####※※※※※", "※※####语音20140808语音范围内####※※");
					v.setBackgroundResource(R.drawable.hold_to_talk_normal);
					rcChat_popup.setVisibility(View.VISIBLE);
					voice_rcd_hint_loading.setVisibility(View.VISIBLE);
					voice_rcd_hint_rcding.setVisibility(View.GONE);
					voice_rcd_hint_tooshort.setVisibility(View.GONE);
					voice_rcd_hint_toolong.setVisibility(View.GONE);
					volumeImagehandler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								voice_rcd_hint_loading.setVisibility(View.GONE);
								voice_rcd_hint_rcding
										.setVisibility(View.VISIBLE);
							}
						}
					}, 300);
					img1.setVisibility(View.VISIBLE);
					del_re.setVisibility(View.GONE);
					startVoiceT = SystemClock.currentThreadTimeMillis();
					RingRecordFilePath = getAmrPath();
					start(RingRecordFilePath);
//    				}else if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
    				}else if (event.getY() < 0) {//手势按下的位置不在语音录制按钮的范围内
    					Log.e("※※※※※####语音20140808语音不在范围内####※※※※※", "※※####语音20140808语音不在范围内####※※");
    					System.out.println("5");
//    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc);
//    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc2);
    					img1.setVisibility(View.GONE);
    					del_re.setVisibility(View.VISIBLE);
//    					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
//    					if (event.getY() >= del_Y
//    							&& event.getY() <= del_Y + del_re.getHeight()
//    							&& event.getX() >= del_x
//    							&& event.getX() <= del_x + del_re.getWidth()) {
    						del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
//    						sc_img1.startAnimation(mLitteAnimation);
//    						sc_img1.startAnimation(mBigAnimation);
//    					}
    				}else {
    					Log.e("※※※※※####语音20140808语音其它####※※※※※", "※※####语音20140808语音其它####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
    				}
    				break;
				default:
					if (event.getY() > 0 && event.getX() > btn_rc_X) {
						Log.e("※※※※※####语音20140808语音范围内2####※※※※※", "※※####语音20140808语音范围内2####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
					}else if (event.getY() < 0) {//手势按下的位置不在语音录制按钮的范围内
    					Log.e("※※※※※####语音20140808语音不在范围内####※※※※※", "※※####语音20140808语音不在范围内####※※");
    					System.out.println("5");
//    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc);
//    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
//    							R.anim.cancel_rc2);
    					Animation mLitteAnimation = AnimationUtils.loadAnimation(mContext,
						R.anim.zoom_enter);
    					Animation mBigAnimation = AnimationUtils.loadAnimation(mContext,
						R.anim.zoom_exit);
    					img1.setVisibility(View.GONE);
    					del_re.setVisibility(View.VISIBLE);
//    					del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
//    					if (event.getY() >= del_Y
//    							&& event.getY() <= del_Y + del_re.getHeight()
//    							&& event.getX() >= del_x
//    							&& event.getX() <= del_x + del_re.getWidth()) {
    						del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
    						sc_img1.startAnimation(mLitteAnimation);
    						sc_img1.startAnimation(mBigAnimation);
//    					}
    				}else {
    					Log.e("※※※※※####语音20140808语音其它####※※※※※", "※※####语音20140808语音其它####※※");
    					img1.setVisibility(View.VISIBLE);
    					del_re.setVisibility(View.GONE);
    					del_re.setBackgroundResource(0);
    				}
					break;
    			}

    			return true;
    		}
    	});
        //voice_text end
    }
    
	public void initAudioRecordView(){
		volume = (ImageView) this.findViewById(R.id.volume);
		rcChat_popup = this.findViewById(R.id.rcChat_popup);
		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);
		voice_rcd_hint_toolong = (LinearLayout) this
		.findViewById(R.id.voice_rcd_hint_toolong);
//		mr = new AudioRecorder();
//		mr = new ARecorder();
//		mr.initRecorder();
		
//		initMediaplayer();
//		/* 监听播放是否完成 */
//		mMediaPlayer.setOnCompletionListener(this);
	}
	private static final int POLL_INTERVAL = 300;

	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};
	private Runnable mPollTask = new Runnable() {
		public void run() {
			if (recodeTime >= MAX_TIME && MAX_TIME != 0){//录音超过15秒自动停止
				stop();
			}else{
//				double amp = mr.getAmplitude();
//				updateDisplay(amp);
				recodeTime += 0.2;
				volumeImagehandler.postDelayed(mPollTask, POLL_INTERVAL);
			}
		}
	};

	private void start(String name) {
		recodeTime = 0.0f;
		try{
////		mr.start(name);
//		mr.mIsRecording = true;
//		mr.mRecorder.startRecording();
////		 * mRawFile = getFile("raw");
//		mr.startBufferedWrite(new File(name));
			// 设置输出文件
            recorder.setOutputFile(name);
            recorder.prepare();
            recorder.start();
		}catch(Exception e){}
		
		volumeImagehandler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private void stop() {
		volumeImagehandler.removeCallbacks(mSleepTask);
		volumeImagehandler.removeCallbacks(mPollTask);
		try{
////		mr.stop();
//			mr.mIsRecording = false;
//			mr.mRecorder.stop();
//			mr.mRecorder.release();
//			mr.mRecorder = null;
			recorder.reset();

			//jspeex 压缩与解压缩需要放到thread中处理 start
//		JSEncode jsencode = new JSEncode();
//		jsencode.initEncoder();
//		String mRawFile = RingRecordFilePath;
//		String mEncodedFile = RingRecordFilePath.replaceAll(".raw", ".spx");
//		try {
//			jsencode.encodeFile(new File(mRawFile), new File(mEncodedFile));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		JSpeexDec decoder = new JSpeexDec();
//		String destPath = RingRecordFilePath.replaceAll(".raw", "_decode.raw");
//		decoder.decode(new File(mEncodedFile), new File (destPath));
		//jspeex 压缩与解压缩需要放到thread中处理 end
			decode();
		}catch(Exception e){
			e.printStackTrace();
		}
		volume.setImageResource(R.drawable.amp1);
	}
	
	private void decode() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
				loadingDialog.show();
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
				try{
					//jspeex 压缩与解压缩需要放到thread中处理 start
					JSEncode jsencode = new JSEncode();
					jsencode.initEncoder();
					String mRawFile = RingRecordFilePath;
					String mEncodedFile = RingRecordFilePath.replaceAll(".raw", ".spx");
					try {
						jsencode.encodeFile(new File(mRawFile), new File(mEncodedFile));
					} catch (IOException e) {
						e.printStackTrace();
					}
					JSpeexDec decoder = new JSpeexDec();
					String destPath = RingRecordFilePath.replaceAll(".raw", "_decode.raw");
					decoder.decode(new File(mEncodedFile), new File (destPath));
					//jspeex 压缩与解压缩需要放到thread中处理 end
				}catch(Exception e){
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				loadingDialog.dismiss();
				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
				} else {
//					mHandler2.sendEmptyMessage(0);
				}
			}

		});
	}
	
	private void updateDisplay(double signalEMA) {
		
		switch ((int) signalEMA) {
		case 0:
		case 1:
			volume.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			volume.setImageResource(R.drawable.amp2);
			
			break;
		case 4:
		case 5:
			volume.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			volume.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			volume.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			volume.setImageResource(R.drawable.amp6);
			break;
		default:
			volume.setImageResource(R.drawable.amp7);
			break;
		}
	}

	//获取文件手机路径
	private String getAmrPath(){
		File file = new File(setMkdir(PHOTOPATH2),getRingRecordFileName());
		return file.getAbsolutePath();
	}
	//删除老文件
	void scanOldFile(){
//		File file = new File(Environment  
//                .getExternalStorageDirectory(), "my/voice.amr");
		File file = new File(RingRecordFilePath);
		if(file.exists()){
			file.delete();
		}
	}
    /** 
     * 保存文件文件到目录 
     * @param context 
     * @return  文件保存的目录 
     */  
    public String setMkdir(String myrelativefilepath)  
    {  
        String filePath;  
        if(checkSDCard())  
        {  
//            filePath = Environment.getExternalStorageDirectory()+File.separator+"myfilepath"; 
            filePath = Environment.getExternalStorageDirectory()+File.separator+myrelativefilepath+File.separator;
        }else{  
//            filePath = context.getCacheDir().getAbsolutePath()+File.separator+"myfilepath";  
            filePath = this.getCacheDir().getAbsolutePath()+File.separator+myrelativefilepath+File.separator; 
        }  
        File file = new File(filePath);  
        if(!file.exists())  
        {  
            boolean b = file.mkdirs();  
//            Log.e("file", "文件不存在  创建文件    "+b);  
        }else{  
//            Log.e("file", "文件存在");  
        }  
        return filePath;  
    } 
    /** 
     * 检验SDcard状态 
     * @return boolean 
     */  
    public boolean checkSDCard()  
    {  
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))  
        {  
            return true;  
        }else{  
            return false;  
        }  
    }
    
	
    public void initAdd() {
        tv_weather = (TextView) findViewById(R.id.tv_weather);
//        tv_xingzuo = (TextView) findViewById(R.id.tv_xingzuo);
        tv_joke = (TextView) findViewById(R.id.tv_joke);
        tv_loc = (TextView) findViewById(R.id.tv_loc);
        tv_gg = (TextView) findViewById(R.id.tv_gg);
        tv_mm = (TextView) findViewById(R.id.tv_mm);
        tv_music = (TextView) findViewById(R.id.tv_music);

        tv_weather.setOnClickListener(this);
        tv_xingzuo.setOnClickListener(this);
        tv_joke.setOnClickListener(this);
        tv_loc.setOnClickListener(this);
        tv_gg.setOnClickListener(this);
        tv_mm.setOnClickListener(this);
        tv_music.setOnClickListener(this);
    }

    public void initData() {
        offset = 0;
        listMsg = msgDao.queryMsg(from, to, offset);
        offset = listMsg.size();
        mLvAdapter = new ChatAdapter(this, listMsg, this);
        mListView.setAdapter(mLvAdapter);
        mListView.setSelection(listMsg.size());
    }

    /**
     * 初始化表情
     */
    private void initViewPager() {
        int pagesize = ExpressionUtil.getPagerCount(staticFacesList.size(), columns, rows);
        Log.d("======pageSize======", pagesize+"");
        // 获取页数
        for (int i = 0; i < pagesize; i++) {
            views.add(ExpressionUtil.viewPagerItem(this, i, staticFacesList, columns, rows, input));
            LayoutParams params = new LayoutParams(16, 16);
            mDotsLayout.addView(dotsItem(i), params);
        }
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        mViewPager.setAdapter(mVpAdapter);
        mDotsLayout.getChildAt(0).setSelected(true);
    }

    /**
     * 表情页切换时，底部小圆点
     *
     * @param position
     * @return
     */
    private ImageView dotsItem(int position) {
        View layout = inflater.inflate(R.layout.dot_image, null);
        ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
        iv.setId(position);
        return iv;
    }


    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        switch (arg0.getId()) {
            case R.id.net_status_bar_btn:
            	setNetworkMethod(this);
            	break;
            case R.id.send_sms://发送
                String content = input.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                sendMsgText(content, true);
                break;
            case R.id.input_sms://点击输入框
                if (chat_face_container.getVisibility() == View.VISIBLE) {
                    chat_face_container.setVisibility(View.GONE);
                }
                if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_face://点击表情按钮
                hideSoftInputView();//隐藏软键盘
                if (chat_add_container.getVisibility() == View.VISIBLE) {
                    chat_add_container.setVisibility(View.GONE);
                }
                if (chat_face_container.getVisibility() == View.GONE) {
                    chat_face_container.setVisibility(View.VISIBLE);
                } else {
                    chat_face_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_add://点击加号按钮
                hideSoftInputView();//隐藏软键盘
                if (chat_face_container.getVisibility() == View.VISIBLE) {
                    chat_face_container.setVisibility(View.GONE);
                }
                if (chat_add_container.getVisibility() == View.GONE) {
                    chat_add_container.setVisibility(View.VISIBLE);
                } else {
                    chat_add_container.setVisibility(View.GONE);
                }
                break;
            case R.id.image_voice://点击语音按钮
            	voice_text.setVisibility(View.VISIBLE);
            	input.setVisibility(View.GONE);
                image_voice.setVisibility(View.GONE);
                image_keyboard.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(voice_type) && voice_type.equals("1")) {//以语音形式发送
//                    speechRecognizerUtil.say(input, false);
                } else {//以文本形式发送
//                    speechRecognizerUtil.say(input, true);
                }
                break;
//            case R.id.voice_text://长按录音
//            	break;
            case R.id.image_keyboard://点击键盘文字输入按钮
            	voice_text.setVisibility(View.GONE);
            	input.setVisibility(View.VISIBLE);
                image_voice.setVisibility(View.VISIBLE);
                image_keyboard.setVisibility(View.GONE);
                break;
            case R.id.tv_weather:
                sendMsgText(PreferencesUtils.getSharePreStr(this, Const.CITY) + "天气", true);
                break;
//            case R.id.tv_xingzuo:
//                input.setText("星座#");
//                input.setSelection(input.getText().toString().length());//光标移至最后
//                changeList(Const.MSG_TYPE_TEXT, "请输入星座#您的星座查询");
//                chat_add_container.setVisibility(View.GONE);
//                showSoftInputView(input);
//                break;
            case R.id.tv_joke:
                sendMsgText("笑话", true);
                break;
            case R.id.tv_loc:
                sendMsgText("位置", false);
                String lat = PreferencesUtils.getSharePreStr(this, Const.LOCTION);//经纬度
                if (TextUtils.isEmpty(lat)) {
                    lat = "116.404,39.915";//北京
                }
                changeList(Const.MSG_TYPE_LOCATION, Const.LOCATION_URL_S + lat + "&markers=|" + lat + "&markerStyles=l,A,0xFF0000");//传入地图（图片）路径
                break;
            case R.id.tv_gg:
                sendMsgText("帅哥", true);
                break;
            case R.id.tv_mm:
                sendMsgText("美女", true);
                break;
            case R.id.tv_music:
                input.setText("歌曲##");
                input.setSelection(input.getText().toString().length() - 1);
                changeList(Const.MSG_TYPE_TEXT, "请输入：歌曲#歌曲名#演唱者");
                chat_add_container.setVisibility(View.GONE);
                showSoftInputView(input);
                break;
        }
    }

    /**
     * 执行发送消息 文本类型
     * isReqApi 是否调用api回答问题
     *
     * @param content
     */
    void sendMsgText(String content, boolean isReqApi) {
        if (content.endsWith("##")) {
            ToastUtil.showToast(this, "输入有误");
            return;
        }
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_TEXT);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mLvAdapter.notifyDataSetChanged();
        input.setText("");
        sendMsgIQ();
        if (isReqApi) getFromMsg(Const.MSG_TYPE_TEXT, content);
    }

    /**
     * 执行发送消息 图片类型
     */
    void sendMsgImg(String imgpath) {
        Msg msg = getChatInfoTo(imgpath, Const.MSG_TYPE_IMG);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mLvAdapter.notifyDataSetChanged();

    }

    /**
     * 执行发送消息 位置类型
     *
     * @param content
     */
    void sendMsgLocation(String content) {
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_LOCATION);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mLvAdapter.notifyDataSetChanged();
    }

    /**
     * 发送语音
     *
     * @param content
     */
    void sendMsgVoice(String content) {
        String[] _content = content.split(Const.SPILT);
        Msg msg = getChatInfoTo(content, Const.MSG_TYPE_VOICE);
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mLvAdapter.notifyDataSetChanged();
        getFromMsg(Const.MSG_TYPE_TEXT, _content[1]);
    }

    /**
     * 发送的信息
     * from为收到的消息，to为自己发送的消息
     *
     * @return
     */
    private Msg getChatInfoTo(String message, int msgtype) {
        String time = sd.format(new Date());
        Msg msg = new Msg();
        msg.setFromUser(from);
        msg.setToUser(to);
        msg.setType(msgtype);
        msg.setIsComing(1);
        msg.setContent(message);
        msg.setDate(time);
        return msg;
    }

    /**
     * 获取结果
     *
     * @param msgtype
     * @param info
     */
    private void getFromMsg(final int msgtype, String info) {
        if (info.startsWith("星座#") && info.length() > 3) {
            getResponse(msgtype, info.split("#")[1] + "运势");
        } else if (info.startsWith("歌曲#") && info.split("#").length == 3) {
            String[] _info = info.split("#");
            if (TextUtils.isEmpty(_info[1]) || TextUtils.isEmpty(_info[2])) {
                ToastUtil.showToast(this, "输入有误");
                return;
            }
            getMusic(_info[1], _info[2]);
        } else {
            getResponse(msgtype, info);
        }
    }

    /**
     * 调用机器人api获取回答结果
     *
     * @param msgtype
     * @param info
     */
    void getResponse(final int msgtype, String info) {
        ajaxParams=new AjaxParams();
        ajaxParams.put("key",Const.ROBOT_KEY);
        ajaxParams.put("info",info);
        fh.post(Const.ROBOT_URL,ajaxParams, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                LogUtil.e("response>>" + o);
                Answer answer = PraseUtil.praseMsgText((String) o);
                String responeContent;
                if (answer == null) {
                    responeContent = "网络错误";
                    changeList(msgtype, responeContent);
                } else {
                    switch (answer.getCode()) {
                        case 40001://参数key错误
                        case 40002://请求内容info为空
                        case 40004://当天请求次数已使用完
                        case 40007://数据格式异常
                        case 100000://文本
                            responeContent = answer.getText();
                            changeList(msgtype, responeContent);
                            break;
                        case 200000://链接
                            responeContent = answer.getText() + answer.getUrl();
                            changeList(msgtype, responeContent);
                            break;
                        case 302000://新闻
                        case 308000://菜谱
                            responeContent=answer.getJsoninfo();
                            changeList(Const.MSG_TYPE_LIST, responeContent);
                            break;
                    }
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                changeList(msgtype, "网络连接失败");
            }
        });
    }

    /**
     * 获取音乐链接
     *
     * @param name
     * @param author
     */
    void getMusic(final String name, final String author) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Music music = MusicSearchUtil.searchMusic(name, author);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = music;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 刷新数据
     *
     * @param msgtype
     * @param responeContent
     */
    private void changeList(int msgtype, String responeContent) {
        Msg msg = new Msg();
        msg.setIsComing(0);
        msg.setContent(responeContent);
        msg.setType(msgtype);
        msg.setFromUser(from);
        msg.setToUser(to);
        msg.setDate(sd.format(new Date()));
        msg.setMsgId(msgDao.insert(msg));
        listMsg.add(msg);
        offset = listMsg.size();
        mLvAdapter.notifyDataSetChanged();
        if (msg.getType()==Const.MSG_TYPE_TEXT) {
            String speech_type = PreferencesUtils.getSharePreStr(this, Const.IM_SPEECH_TPPE);
            if (!TextUtils.isEmpty(speech_type) && speech_type.equals("1")) {
//                speechSynthesizerUtil.speech(msg.getContent());
            }
        }

    }

    @Override
    public void click(int position) {//点击
        Msg msg = listMsg.get(position);
        switch (msg.getType()) {
            case Const.MSG_TYPE_TEXT://文本
                break;
            case Const.MSG_TYPE_IMG://图片
                break;
            case Const.MSG_TYPE_LOCATION://位置
                Intent intent = new Intent(this, ImgPreviewActivity.class);
                intent.putExtra("url", msg.getContent());
                startActivity(intent);
                break;
            case Const.MSG_TYPE_VOICE://语音

                break;
            case Const.MSG_TYPE_MUSIC://音乐
                String[] musicinfo = msg.getContent().split(Const.SPILT);
                if (musicinfo.length == 3) {//音乐链接，歌曲名，作者
                    if (TextUtils.isEmpty(msg.getBak1()) || msg.getBak1().equals("0")) {
                        stopOldMusic();
                        msg.setBak1("1");
                        listMsg.remove(position);
                        listMsg.add(position, msg);
                        mLvAdapter.notifyDataSetChanged();
                        playMusic(musicinfo);
                    } else {
                        if (musicPlayManager != null) {
                            ll_playing.setVisibility(View.GONE);
                            musicPlayManager.stop();
                        }
                        msg.setBak1("0");
                        listMsg.remove(position);
                        listMsg.add(position, msg);
                        mLvAdapter.notifyDataSetChanged();
                    }

                }
                break;
        }
    }

    @Override
    public void longClick(int position) {//长按
        Msg msg = listMsg.get(position);
        switch (msg.getType()) {
            case Const.MSG_TYPE_TEXT://文本
                clip(msg, position);
                break;
            case Const.MSG_TYPE_IMG://图片
                break;
            case Const.MSG_TYPE_LOCATION://位置
            case Const.MSG_TYPE_MUSIC://音乐
            case Const.MSG_TYPE_VOICE://语音
            case Const.MSG_TYPE_LIST://列表
                delonly(msg, position);
                break;
        }
    }

    /**
     * 播放网络音乐
     *
     * @param musicinfo
     */
    void playMusic(final String[] musicinfo) {
        ll_playing.setVisibility(View.VISIBLE);
        tv_playing.setText("正在播放歌曲：《" + musicinfo[1] + "》—" + musicinfo[2]);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    musicPlayManager.play(musicinfo[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e("音乐播放异常>>" + e.getMessage());
                    stopOldMusic();
                    Looper.prepare();
                    ToastUtil.showToast(ChatActivity.this, "播放错误，请重试");
                    Looper.loop();
                }
            }
        }).start();
    }

    /**
     * 停止之前正在播放的音乐
     */
    void stopOldMusic() {
        for (int i = 0; i < listMsg.size(); i++) {
            Msg msg = listMsg.get(i);
            if (!TextUtils.isEmpty(msg.getBak1()) && msg.getBak1().equals("1")) {
                msg.setBak1("0");
                listMsg.remove(i);
                listMsg.add(i, msg);
                mLvAdapter.notifyDataSetChanged();
                if (musicPlayManager != null) {
                    ll_playing.setVisibility(View.GONE);
                    musicPlayManager.stop();
                }
                break;
            }
        }
    }

    /**
     * 带复制文本的操作
     */
    void clip(final Msg msg, final int position) {
        new ActionSheetBottomDialog(this)
                .builder()
                .addSheetItem("复制", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        ClipboardManager cmb = (ClipboardManager) ChatActivity.this.getSystemService(ChatActivity.CLIPBOARD_SERVICE);
                        cmb.setText(msg.getContent());
                        ToastUtil.showToast(ChatActivity.this, "已复制到剪切板");
                    }
                })
                .addSheetItem("朗读", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
//                        speechSynthesizerUtil.speech(msg.getContent());
                    }
                })
                .addSheetItem("删除", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        listMsg.remove(position);
                        offset = listMsg.size();
                        mLvAdapter.notifyDataSetChanged();
                        msgDao.deleteMsgById(msg.getMsgId());
                    }
                })
                .show();
    }

    /**
     * 仅有删除操作
     */
    void delonly(final Msg msg, final int position) {
        new ActionSheetBottomDialog(this)
                .builder()
                .addSheetItem("删除", ActionSheetBottomDialog.SheetItemColor.Blue, new ActionSheetBottomDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        listMsg.remove(position);
                        offset = listMsg.size();
                        mLvAdapter.notifyDataSetChanged();
                        msgDao.deleteMsgById(msg.getMsgId());
                        if (msg.getType()==Const.MSG_TYPE_MUSIC) {
                            if (musicPlayManager != null) {
                                ll_playing.setVisibility(View.GONE);
                                musicPlayManager.stop();
                            }
                        }
                    }
                })
                .show();
    }

//    /**
//     * 录音完毕
//     * text 录音转文字后的内容
//     */
//    @Override
//    public void recoComplete(String text) {
//        String voicepath = Const.FILE_VOICE_CACHE + System.currentTimeMillis() + ".wav";
//        if (SysUtils.copyFile(Const.FILE_VOICE_CACHE + "iat.wav", voicepath)) {
//            sendMsgVoice(voicepath + Const.SPILT + text);
//        } else {
//            ToastUtil.showToast(this, "录音失败");
//        }
//    }

    /**
     * 表情页改变时，dots效果也要跟着改变
     */
    class PageChange implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
                mDotsLayout.getChildAt(i).setSelected(false);
            }
            mDotsLayout.getChildAt(arg0).setSelected(true);
        }
    }

    /**
     * 下拉加载更多
     */
    @Override
    public void onRefresh() {
        List<Msg> list = msgDao.queryMsg(from, to, offset);
        if (list.size() <= 0) {
            mListView.setSelection(0);
            mListView.onRefreshCompleteHeader();
            return;
        }
        listMsg.addAll(0, list);
        offset = listMsg.size();
        mListView.onRefreshCompleteHeader();
        mLvAdapter.notifyDataSetChanged();
        mListView.setSelection(list.size());
    }


    @Override
    protected void onResume() {
        super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //让输入框获取焦点
                input.requestFocus();
                if (chat_face_container.getVisibility() == View.VISIBLE || chat_add_container.getVisibility() == View.VISIBLE) {
                    hideSoftInputView();
                }
            }
        }, 100);

    }

    /**
     * 监听返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	if((chat_face_container.getVisibility() == View.GONE)
        			&& (chat_add_container.getVisibility() == View.GONE)
        			&& (musicPlayManager == null || !musicPlayManager.isPlaying())){
        		if(event.getRepeatCount() == 0){
        			Log.d("================20170507 ChatActivity onBackPressed================", "+++++++onBackPressed+++++++jid="+jid);
        			//通知ContactListPullRefListActivity更新局部 消息图章为0，不显示消息图章
        			Intent i = new Intent(ChatActivity.this,ContactFrameActivity.class);//ContactListPullRefListActivity
        			i.putExtra("jid",jid);
        			startActivity(i);
        			finish();
        		}
        		
        	}else{
            hideSoftInputView();
            if (chat_face_container.getVisibility() == View.VISIBLE) {
                chat_face_container.setVisibility(View.GONE);
            } else if (chat_add_container.getVisibility() == View.VISIBLE) {
                chat_add_container.setVisibility(View.GONE);
            } else {
                if (musicPlayManager != null && musicPlayManager.isPlaying()) {
                    musicPlayManager.stop();
                }
//                if (speechSynthesizerUtil != null) {
//                    speechSynthesizerUtil.stopSpeech();
//                }
                finish();
            }
        	}
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获取录音时动画效果的图片
     */
    public static Drawable[] getRecordAnimPic(Resources res) {
        return new Drawable[]{res.getDrawable(R.drawable.amp1),
                res.getDrawable(R.drawable.amp2), res.getDrawable(R.drawable.amp3),
                res.getDrawable(R.drawable.amp4), res.getDrawable(R.drawable.amp5),
                res.getDrawable(R.drawable.amp6), res.getDrawable(R.drawable.amp7)};
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		
		
// 	    XmppConnectionAdapter.isPause = true;
////		if(XmppConnectionAdapter.instance!=null)
////			XmppConnectionAdapter.instance.resetApplication();
//		XmppConnectionAdapter.instance = null;
//		stopService(SERVICE_INTENT);
//		loadingView.isStop = true;
	    try{
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}

		mXmppFacade = null;
		
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		clearAsyncTask();
    }
    
    
    
//	private View mNetErrorView;
//	private TextView mConnect_status_info;
//	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    
    private static final Intent SERVICE_INTENT = new Intent();
	static {
		//pkg,cls
//		SERVICE_INTENT.setComponent(new ComponentName("com.test", "com.stb.isharemessage.BeemService"));
//		SERVICE_INTENT.setComponent(new ComponentName("com.stb.isharemessage", "com.stb.isharemessage.BeemService"));
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
	private final ServiceConnection mServConn = new BeemServiceConnection();
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(ChatActivity.this);
		    		
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    try{
			    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
			    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
		    }catch (RemoteException e) {
		    	e.printStackTrace();
		    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }
    
	private void sendMsgIQ() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				sendMsgIQ_fuc();
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				if (!result) {
//					showCustomToast("数据加载失败...");
//					mHandler2.sendEmptyMessage(3);
				} else {
//					mHandler2.sendEmptyMessage(0);
				}
			}

		});
	}
    
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
    boolean sendMsgIQ_fuc(){
		if(BeemConnectivity.isConnected( getApplicationContext())){
			Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()222++++++++++++++");
		    try {
		    	if(mXmppFacade!=null){
		    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()333++++++++++++++");
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		MsgIQ reqXML = new MsgIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setMsgType1(0);
			            reqXML.setMsgType2(0);
			            String partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
			            reqXML.setPartnerid(partnerid);
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
					    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
			            reqXML.setFromUserUuid(uuid);
			            reqXML.setToUserUuid(uuid);
//			            String hashcode = "";//partnerid+touserUuid+fromUserUuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = partnerid+ uuid+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHash(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "msgiq"; 
			    		String namespace = "com:isharemessage:msgiq";
			    		ContactGroupListIQResponseProvider provider = new ContactGroupListIQResponseProvider();
//			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "msgiq", "com:isharemessage:msgiq", provider);
//			            String retcode = "";
//			            if(rt!=null){
//			                if (rt instanceof MsgIQResponse) {
//			                	final MsgIQResponse msgIQResponse = (MsgIQResponse) rt;
//
//			                    if (msgIQResponse.getChildElementXML().contains(
//			                            "com:isharemessage:msgiq")) {
////			    					ChatActivity.this.runOnUiThread(new Runnable() {
////				                    	
////            							@Override
////            							public void run() {
////            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
////            							}
////            						});
//			                        retcode = msgIQResponse.getRetcode();
//			                        
//			                    }
//			                } 
//			            }
//			            
//			    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");
//
//			    	    if(retcode!=null && retcode.equalsIgnoreCase("0000")){
//			    	    	errorType = 5;
//			    	    	return true;
//			    	    }else{
//			    	    	if(retcode!=null && !retcode.equalsIgnoreCase("0000"))
//			    	    		errorType = 0;
//			    	    	else
//			    	    		errorType = 6;
//			    	    }
			    		mXmppFacade.getXmppConnectionAdapter().getAdaptee().sendPacket(reqXML);//异步方式
						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
    }
    
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接中...");
				break;
			case 3:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
//				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
				break;
			case 5:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
//					mNetErrorView.setVisibility(View.VISIBLE);
//					if(BeemConnectivity.isConnected(mContext))
//					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{

		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
//			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
}

